package cn.sixmillions.yuqueblog.service.impl;

import cn.hutool.http.HttpRequest;
import cn.sixmillions.yuqueblog.config.YuQueProperties;
import cn.sixmillions.yuqueblog.entity.User;
import cn.sixmillions.yuqueblog.service.IUserService;
import cn.sixmillions.yuqueblog.utils.RedisUtil;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import static cn.sixmillions.yuqueblog.common.constant.YuQueConstant.*;

/**
 * @description: 用户接口实现
 * @author: sixmillions
 * @since: 2021/12/10
 **/
@Service
@Slf4j
public class UserServiceImpl implements IUserService {

    @Autowired
    private YuQueProperties conf;

    @Override
    public User getUserInfo(String login) {
        String cacheKey = String.format(USER_CACHE_KEY, login);
        String userStr = RedisUtil.StringOps.get(cacheKey);
        if (StringUtils.isNotBlank(userStr)) {
            //从缓存获取
            return JSON.parseObject(userStr, User.class);
        }
        // 请求语雀API
        String requestUrl = String.format(USER_URL, login);
        String reponseRes = HttpRequest.get(requestUrl).header(AUTH_HEADER, conf.getToken()).execute().body();
        String userInfoStr = JSON.parseObject(reponseRes).getString("data");
        RedisUtil.StringOps.set(cacheKey, userInfoStr);
        return JSON.parseObject(userInfoStr, User.class);
    }
}
